﻿using google.protobuf;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class testProto : MonoBehaviour
{
    //将protobuf对象序列化位byte数组
    public static byte[]Encode(ProtoBuf.IExtensible msgBase)
    {
        using(var memory=new System.IO.MemoryStream())
        {
            ProtoBuf.Serializer.Serialize(memory, msgBase);
            return memory.ToArray();
        }
    }
    //解码
    public static ProtoBuf.IExtensible Decode(string protoName,byte[]bytes,int offset,int count)
    {
        using(var memory=new System.IO.MemoryStream(bytes, offset, count))
        {
            System.Type t = System.Type.GetType(protoName);
            return (ProtoBuf.IExtensible)ProtoBuf.Serializer.NonGeneric.Deserialize(t, memory);
        }
    }
    void Start()
    {
        //protobuf 测试 编码
        MsgMove msgMove = new MsgMove();
        msgMove.X = 214;
        byte[] bs = Encode(msgMove);
        Debug.Log(System.BitConverter.ToString(bs));
        //解码
        ProtoBuf.IExtensible m = Decode(msgMove.ToString(), bs, 0, bs.Length);
        MsgMove m2 = (MsgMove)m;
        Debug.Log(m2.X);
    }
}
